﻿using Microsoft.AspNetCore.Mvc;
using NorthwindDataservice;
using NorthwindWebservice.ViewModels;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;

namespace NorthwindWebservice.Controllers
{
    [Route("api/products")]
    public class ProductsController : Controller
    {
        DataService _dataService;

        //Dependency Injection
        public ProductsController(DataService dataService)
        {
            _dataService = dataService;
        }


        // I'm not quite sure if this is the right way to pass the test. Name of test indicates it should return "more" than a simple anonymous product.
        // could for sure be made more dynamic.
        [HttpGet("{id}")]
        public IActionResult GetProductById(int id)
        {
            var product = _dataService.GetProduct(id);

            if (product == null)
            {
                return NotFound();
            }

            var productVM = new ProductVM(product.Name, product.Category.Name);

            return Ok(productVM);
        }

        [HttpGet("name/{name}")]
        public IActionResult ListProducts(string name)
        {
            var products = _dataService.GetProductByName(name);
            if (products.Count == 0) return NotFound(products);
            else return Ok(products);

        }

        [HttpGet("category/{Id}")]
        public IActionResult GetProductsByCategoryId(int Id)
        {
            var products = _dataService.GetProductByCategory(Id);

            if (products.Count == 0)
            {
                return NotFound(products);
            }

            var productAltVMs = new List<ProductAltVM>();

            foreach (var p in products)
            {
                productAltVMs.Add(new ProductAltVM(p.Name, p.Category.Name));
            }

            return Ok(productAltVMs);
        }


        public IActionResult Index()
        {
            return Ok();
        }
    }
}